<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content"></div>
    <button id="btn">导出</button>
    <!-- 第三方库 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html-docx-js/dist/html-docx.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/file-saver/dist/FileSaver.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
    <script>
        $(document).ready(function () {
            fetch('./test.txt')
                .then(res => res.text())
                .then(text => {
                    htmlContent = text;
                    $('#content').html(htmlContent);
                });
        });
        // 导出为 Word 文档
        function exportToWord(html, fileName = '文档内容.docx') {

            const fullHtml = '<!DOCTYPE html>' +
                '<html>' +
                '<head>' +
                '<meta charset="UTF-8">' +
                '<style>*{font-family:"宋体",SimSun,sans-serif;}body{width:100%;margin:0;padding:20px;}</style>' +
                '</head>' +
                '<body>' +
                html +
                '</body>' +
                '</html>';
            try {
                const blob = htmlDocx.asBlob(fullHtml);
                saveAs(blob, fileName);
            } catch (e) {
                console.error("导出 Word 出错：", e);
                alert("导出失败，请查看控制台日志");
            }
        }

        // 按钮点击事件
        $("#btn").click(function () {
            console.log(1231231);
            if (!htmlContent) {
                alert("内容尚未加载完成");
                return;
            }

            // ✅ 使用 htmlDocx 导出 Word
            exportToWord(htmlContent);

            // 可选：导出 PDF（保留）
            // exportToPDF();
        });
    </script>
</body>

</html>